import { useEffect, useState } from "react";
import { Cursor } from "./cursor";

interface AnimateTypeProps {
  rotateText: string[];
}

export function AnimateType({ rotateText }: AnimateTypeProps) {
  const [text, setText] = useState("");
  const [isDeleting, setIsDeleting] = useState(false);
  const [typeSpeed, setTypeSpeed] = useState(150);
  const [index, setIndex] = useState(0);
  // const letters = "Hello World!";
  // const rotateText = [
  //   "UI/UX Designer",
  //   "Frontend developer",
  //   "Backend developer",
  // ];
  useEffect(() => {
    const switchSpeed = 3000;
    const tick = () => {
      const letters = rotateText[index];
      const currentText = isDeleting
        ? letters.slice(0, text.length - 1)
        : letters.slice(0, text.length + 1);
      setText(currentText);
      if (isDeleting && currentText === "") {
        setIsDeleting(false);
        setTypeSpeed(switchSpeed);
        const i = index + 1;
        setIndex(i % rotateText.length);
      } else if (!isDeleting && currentText === letters) {
        setIsDeleting(true);
        setTypeSpeed(switchSpeed);
      } else {
        if (isDeleting) {
          setTypeSpeed(typeSpeed / 2);
        }
        setTypeSpeed(150);
      }
    }

    const ticker = setInterval(tick, typeSpeed);
    return () => clearInterval(ticker);
  }, [text, isDeleting, typeSpeed, rotateText, index]);

  return (
    <div>
      <span>{text}</span>
      <Cursor isBlinking={typeSpeed === 3000} />
    </div>
  );
}